package itsm.isperp.module.utils;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.utils.NetUtils;
import itsm.isperp.module.entity.app.AppLoginLog;
import itsm.isperp.module.entity.app.AppUser;
import itsm.isperp.module.service.app.AppLoginLogService;
import itsm.isperp.module.service.app.AppUserService;

import java.sql.Timestamp;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.security.web.authentication.session.CompositeSessionAuthenticationStrategy;

/**
 * 
 * 
 * 
 * @author lizx
 * @date 2015-12-18
 * @since 1.0
 * 
 */
public final class LoginUtils {

	public final static UserDetails login(String username, String info,
			HttpServletRequest request, HttpServletResponse response)
			throws AuthenticationException, Exception {

		AuthenticationManager authenticationManager = ContextHolder
				.getSpringBean("isperp.authenticationManager");
		AppUserService appUserService = ContextHolder
				.getSpringBean("appUserService");
		AppUser u = (AppUser) appUserService.loadUserByUsername(username);


		UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
				u.getUsername(), u.getPassword());

		token.setDetails(new WebAuthenticationDetails(ContextHolder
				.getRequest()));
		Authentication authenticatedUser = authenticationManager
				.authenticate(token);

		SecurityContextHolder.getContext().setAuthentication(authenticatedUser);

		CompositeSessionAuthenticationStrategy concurrentSessionControlStrategy = ContextHolder
				.getSpringBean("concurrentSessionControlStrategy");
		concurrentSessionControlStrategy.onAuthentication(authenticatedUser,
				request, response);

		AppLoginLogService appLoginLogService = ContextHolder
				.getSpringBean("appLoginLogService");
		AppLoginLog log = new AppLoginLog();
		log.setCreatedDate(new Timestamp(new Date().getTime()));
		log.setInfo(info);
		log.setIp(NetUtils.getIpAddr(request));
		log.setSuccess(true);
		log.setUsername(u.getUsername());
		appLoginLogService.saveOrUpdate(log);
		return u;
	}
}
